//
//  JKNetworkingTool.swift
//  ZhiHuDaily-Swift
//
//  Created by albert on 2018/3/5.
//  Copyright © 2018年 安永博. All rights reserved.
//

import UIKit
import Alamofire
import HandyJSON

class JKNetworkingTool {
    
    static let shared = JKNetworkingTool()
    
    var baseUrl = "https://news-at.zhihu.com/api/4/"
    var baseParams:NSMutableDictionary = [:]
    let baseHeaders: HTTPHeaders = [
//        "Accept" : "text/plain",
        "Accept" : "application/json",
//        "Accept" : "text/json",
//        "Accept" : "text/javascript",
//        "Accept" : "text/css"
    ]
    
    // MARK: - 拼接完整的url

    /** 拼接完整的url */
    private func getCompleteUrl(urlStr: String) -> String {
        
        let completeUrl = baseUrl.appending(urlStr)
        
        return completeUrl
    }
    
    // MARK: - 拼接完整的参数
    
    /** 拼接完整的参数 */
    private func getCompleteParams(params: NSDictionary?) -> [String : AnyObject] {
        
        guard let _ = params else { return baseParams as! [String : AnyObject] }
        
        let para = baseParams.mutableCopy() as! NSMutableDictionary
        
        para.addEntries(from: params as! [AnyHashable : Any])
        
        return para as! [String : AnyObject]
    }
    
    // MARK: - 请求方式
    
    /** 请求方式 */
    private func getHttpMethod(method: HTTPMethod) -> HTTPMethod {
        
        if method == HTTPMethod.post {
            
            return .post
            
        }else {
            
            return .get
        }
    }
    
    /** post请求 */
    public func requestPost(url: String,
                            parameters: NSMutableDictionary?,
                            finishedBlock: ((_ responseJson: Any?, _ error: Error?) -> ())?) {
        
        let allParames = getCompleteParams(params: parameters)
        
        request(url: getCompleteUrl(urlStr: url), method: .post, parameters: allParames as? NSMutableDictionary, finishedBlock: finishedBlock)
    }
    
    /** get请求 */
    public func requestGet(url: String,
                            parameters: NSMutableDictionary?,
                            finishedBlock: ((_ responseJson: Any?, _ error: Error?) -> ())?) {
        
        let allParames = getCompleteParams(params: parameters)
        
        request(url: getCompleteUrl(urlStr: url), method: .get, parameters: allParames as? NSMutableDictionary, finishedBlock: finishedBlock)
    }
    
    /** 基础request url要写全 */
    public func request(url          : String,
                        method       : HTTPMethod,
                        parameters   : NSMutableDictionary?,
                        finishedBlock: ((_ responseJson: Any?, _ error: Error?) -> ())?) {
        
        guard let finished = finishedBlock else {
            
            return
        }
        
        UIApplication.shared.isNetworkActivityIndicatorVisible = true
        
        Alamofire.request(url, method: method, parameters: parameters as? [String : AnyObject], encoding: JSONEncoding.default, headers: baseHeaders).responseJSON { (response) in
            
            UIApplication.shared.isNetworkActivityIndicatorVisible = false
            
            switch response.result {
                
            case .success(let value): // 请求成功
                
//                JKLog(message: "Validation Successful\nresult : \(value)")
                
                // 请求成功，但是返回的错误信息，在这里处理一下
                // TODO: 请求成功，但是返回的错误信息，在这里处理一下
                
                finished(value, nil)
                
                break
                
            case .failure(let error): // 请求失败
                
                JKProgressHUD .showError(withStatus: error.localizedDescription)
                
//                JKLog(message: "错误信息: \(error), \n失败的url: \(String(describing: response.request?.url?.absoluteString))")
                
                finished(nil, error)
                
                break
            }
            
            //            if let json = response.result.value {
            //
            //                JKLog(message: "JSON: \(json)") // serialized json response
            //            }
        }
    }
    
    /** 上传图片 */
    public func uploadImage(url: String, parameters: NSMutableDictionary?, photoKey: String) {
        
    }
}
